use std::{
    collections::HashMap,
    fs::{self, File},
    io::Write,
    path::PathBuf,
};


pub fn write_broadcast_output(
    _sn: &String,
    path: &String,
    cwd: Option<String>,
    data: &HashMap<String, String>,
) {

    match url::Url::parse(path) {
        Ok(url) => {
            match url.scheme() {
                "file" => {
                    if url.host_str().is_some() {
                        log::warn!("Path is missing `/`, Path={}", url.path())
                    }
                    // 本地目录
                    write_data_to_file(PathBuf::from(url.path()), cwd, data)
                },
                "ayisha" => {
                    // 远程目录
                    // assert_eq!(url.host_str(), Some("192.168.1.1,192.168.1.2,192.168.1.3"));
                    // assert_eq!(url.port(), None);
                    // assert_eq!(url.path(), "/data/dataxone/sync/srv01/dt_srv01/.ayisha/0.properties");
                    write_data_to_file(PathBuf::from(url.path()), cwd, data)
                    // 1、获取那个是主
                    // 2、将内容远程写入对应的文件中
                }
                _ => {}
            }
        }
        Err(url::ParseError::RelativeUrlWithoutBase) => {
            // 本地路径
            write_data_to_file(PathBuf::from(path), cwd, data)
        },
        Err(e) => {
            log::error!("Url parse error, cause: {e}");
        }
    }
    
}


fn write_data_to_file(mut p: PathBuf, cwd: Option<String>, data: &HashMap<String, String>) {

    log::trace!("write_data_to_file: {:?}", data);

    if !p.has_root() {
        if let Some(cwd) = cwd {
            p = PathBuf::from(&cwd).join(p);
        }
    }

    if let Some(dir) = p.parent() {
        if let Err(e) = fs::create_dir_all(dir) {
            log::error!("Unable to open directory: {}, cause: {e}", &dir.display());
            return;
        }
    }

    match File::create(&p) {
        Ok(mut f) => {
            for (k, v) in data {
                log::trace!("{}={}", k, v);
                if let Err(e) = f.write(format!("{}={}\n", k, v).as_bytes()) {
                    log::error!("Unable to write file: {}, cause: {e}", &p.display())
                }
            }
            f.flush().unwrap();
            log::debug!("Broadcast file written to {}", &p.display());
        }
        Err(e) => log::error!("Unable to open file: {:?}, cause: {e}", &p.display()),
    }
}